//
//  MyReleaseServiceTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/3.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "MyReleaseServiceTabVC.h"
#import "MyReleaseServiceCell.h"
#import "ServiceModel.h"
#import "WriteRequirementTitleCell.h"
@interface MyReleaseServiceTabVC ()<MyReleaseServiceCelllDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) NSMutableArray *editAssociationsArray;
@property(nonatomic,strong) NSMutableArray *releaseAssociationsArray;
@property(nonatomic,assign) NSInteger page;
@property(nonatomic,assign) NSInteger row;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary  *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *associationtype;
@property(nonatomic,strong) NSString *associationtypesub1;
@property(nonatomic,strong) NSString *associationtypesub2;
@property(nonatomic,strong) NSString *commonindustry;
@property(nonatomic,strong) NSString *industry;
@property(nonatomic,assign) NSInteger type;
@property(nonatomic,assign) NSInteger order;
@property(nonatomic,strong) MJRefreshAutoNormalFooter *footer;
@end
static NSString *identifierTitle = @"titleCell";
@implementation MyReleaseServiceTabVC

-(NSMutableArray *)editAssociationsArray
{
    if (!_editAssociationsArray) {
        _editAssociationsArray = [NSMutableArray array];
    }
    return _editAssociationsArray;
}
-(NSMutableArray *)releaseAssociationsArray
{
    if (!_releaseAssociationsArray) {
        _releaseAssociationsArray = [NSMutableArray array];
    }
    return _releaseAssociationsArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.manager = [AFHTTPSessionManager manager];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_header = header;
    [header beginRefreshing];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
    self.tableView.mj_footer = footer;
    [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = [UIFont systemFontOfSize:12];
    footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
//     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(associationrelease:) name:@"associationrelease" object:nil];
    [self.tableView registerNib:[UINib nibWithNibName:@"WriteRequirementTitleCell" bundle:nil] forCellReuseIdentifier:identifierTitle];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateService:) name:@"updateService" object:nil];
}
-(void)updateService:(NSNotification *)info
{
//    self.editAssociationsArray = nil;
//    self.releaseAssociationsArray = nil;
//    self.page = 1;
//    self.row = 10;
    [self refresh];
}

-(void)associationrelease:(NSNotification *)info
{
    
    
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)refresh
{
    self.editAssociationsArray = nil;
    self.releaseAssociationsArray = nil;
    self.page = 1;
    self.row = 10;
    [self reloadInternetData];
    [self.tableView.mj_header endRefreshing];
}
-(void)reloadMore
{
    self.editAssociationsArray = nil;
    self.page ++;
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    [self reloadInternetData];
    
}
-(void)reloadInternetData
{

    NSString *pages = [NSString stringWithFormat:@"%ld",self.page];
    NSString *rows = [NSString stringWithFormat:@"%ld",self.row];
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"page":pages,
                  @"rows":rows,
                  @"token":[UserDefaultsHelper readToken]
                  };
    XLog(@"self.dict:%@",self.dict);
    self.urlString = [NSString stringWithFormat:@"%@/association/release",kUrl];
    
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSDictionary *date = [responseObject objectForKey:@"date"];
        NSArray *editAssociations = [date objectForKey:@"editAssociations"];
        NSArray *releaseAssociations = [date objectForKey:@"releaseAssociations"];
        if (editAssociations.count) {
            for (NSDictionary *dict in editAssociations) {
                ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
                [self.editAssociationsArray addObject:model];
                
            }
//            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView.mj_header endRefreshing];
        XLog(@"editAssociations:%@",editAssociations);
        XLog(@"releaseAssociations:%@",releaseAssociations);
        if (releaseAssociations.count) {
            for (NSDictionary *dict in releaseAssociations) {
                ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
                [self.releaseAssociationsArray addObject:model];
                
            }
            
        }
        XLog(@"releaseAssociations:%ld",releaseAssociations.count);
        XLog(@"editAssociations:%ld",editAssociations.count);
        if (releaseAssociations.count <10) {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }else {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        if (!self.editAssociationsArray.count&&!self.releaseAssociationsArray.count) {
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
             [self.tableView.mj_footer removeFromSuperview];
        }else {
           
        }
        [self.tableView reloadData];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.editAssociationsArray.count?self.editAssociationsArray.count+1:0;
    }else {
        return self.releaseAssociationsArray.count?self.releaseAssociationsArray.count+1:0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
            cell.textLabel.text = @"编辑中服务";
            return cell;
        }else {
            MyReleaseServiceCell *cell = [MyReleaseServiceCell cellNibWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.indexPath = indexPath;
            cell.delegate = self;
            [cell.editingBtn setTitle:@"继续编辑" forState:UIControlStateNormal];
            [cell.editingBtn setTitleColor:[UIColor colorWithRed:152/255.0 green:193/255.0 blue:92/255.0 alpha:1] forState:UIControlStateNormal];
            if (self.editAssociationsArray.count) {
                ServiceModel *model = self.editAssociationsArray[indexPath.row-1];
                cell.serviceModel = model;
            }
            return cell;
            
        }
    }else {
        if (indexPath.row == 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = @"已发布服务";
            return cell;
        }else {
            MyReleaseServiceCell *cell = [MyReleaseServiceCell cellNibWithTableView:tableView];
            cell.indexPath = indexPath;
            cell.delegate = self;
            [cell.editingBtn setTitle:@"修改内容" forState:UIControlStateNormal];
            [cell.editingBtn setTitleColor:[UIColor colorWithRed:242/255.0 green:156/255.0 blue:56/255.0 alpha:1] forState:UIControlStateNormal];
            if (self.releaseAssociationsArray.count) {
                ServiceModel *model = self.releaseAssociationsArray[indexPath.row-1];
                cell.serviceModel = model;
            }
            return cell;
            
        }
    }
   
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 60;
    }else {
        return 135;
    }
}
#pragma mark-代理:删除,编辑
- (void)myReleaseServiceCell:(MyReleaseServiceCell *)myReleaseServiceCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(ServiceModel *)serviceModel
{
    if (clickBtn.tag == 1) {
        NSString *aid = [NSString stringWithFormat:@"%ld",serviceModel.id];
        self.dict = @{
                      @"uid":[UserDefaultsHelper readUid],
                      @"aid":aid,
                      @"token":[UserDefaultsHelper readToken]
                      };
        XLog(@"self.dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/association/delete",kUrl];
        
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *message = [responseObject objectForKey:@"message"];
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
            [self refresh];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else {
        XLog(@"serviceModel:%@",serviceModel);
        if (self.returnValueBlock) {
            self.returnValueBlock(serviceModel,1);
        };
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     ServiceModel *model = self.releaseAssociationsArray[indexPath.row-1];
    if (indexPath.section == 1) {
        if (self.returnValueBlock) {
            self.returnValueBlock(model,0);
        };
    }
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
@end
